<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>充电记录</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563eb',
                        success: '#10b981',
                        warning: '#f59e0b',
                        danger: '#ef4444',
                        gray: {
                            100: '#f3f4f6',
                            200: '#e5e7eb',
                            300: '#d1d5db',
                            400: '#9ca3af',
                            500: '#6b7280',
                            600: '#4b5563',
                            700: '#374151',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .record-card {
                @apply bg-white rounded-lg border border-gray-200 shadow-sm transition-all duration-300 hover:shadow-md hover:translate-y-[-2px];
            }
            .stat-card {
                @apply bg-white rounded-lg border border-gray-200 shadow-sm p-4 transition-all duration-300 hover:shadow-md;
            }
            .status-tag {
                @apply px-2 py-0.5 rounded text-xs font-medium;
            }
            .back-button {
                @apply p-2 rounded-full hover:bg-gray-100 transition-all duration-300 text-gray-600 focus:outline-none focus:ring-2 focus:ring-primary/30 flex items-center justify-center w-10 h-10;
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-md;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-700 min-h-screen">
<header class="bg-white border-b border-gray-200 sticky top-0 z-10 shadow-sm">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <button id="back-button" class="back-button mr-2 md:mr-4" aria-label="返回上一页">
            <i class="fa fa-arrow-left text-gray-700"></i>
        </button>

        <h1 class="text-xl font-semibold flex items-center flex-1">
            <i class="fa fa-bolt text-primary mr-2"></i>
            充电记录
        </h1>
        <span class="text-sm text-gray-500" id="current-date"></span>
    </div>
</header>

<main class="container mx-auto px-4 py-6">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="stat-card card-hover">
            <div class="flex items-center justify-between mb-2">
                <p class="text-gray-500 text-sm">今日有效订单</p>
                <i class="fa fa-file-text-o text-primary text-xl"></i>
            </div>
            <h3 class="text-2xl font-bold" id="stat-orders">0</h3>
            <p class="text-xs text-gray-500 mt-1">仅包含已完成/充电中</p>
        </div>

        <div class="stat-card card-hover">
            <div class="flex items-center justify-between mb-2">
                <p class="text-gray-500 text-sm">总耗电量</p>
                <i class="fa fa-plug text-warning text-xl"></i>
            </div>
            <h3 class="text-2xl font-bold" id="stat-power">0 度</h3>
            <p class="text-xs text-gray-500 mt-1">今日累计充电度数</p>
        </div>

        <div class="stat-card card-hover">
            <div class="flex items-center justify-between mb-2">
                <p class="text-gray-500 text-sm">总收益</p>
                <i class="fa fa-rmb text-success text-xl"></i>
            </div>
            <h3 class="text-2xl font-bold" id="stat-income">¥0.00</h3>
            <p class="text-xs text-gray-500 mt-1">仅统计已完成订单</p>
        </div>
    </div>

    <div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden mb-6">
        <div class="hidden md:grid md:grid-cols-7 gap-2 px-6 py-3 border-b border-gray-200 text-gray-500 text-sm font-medium">
            <div class="col-span-1">设备</div>
            <div class="col-span-1">订单号</div>
            <div class="col-span-1">开始时间</div>
            <div class="col-span-1">结束时间</div>
            <div class="col-span-1">充电量</div>
            <div class="col-span-1">时长</div>
            <div class="col-span-1">状态/费用</div>
        </div>

        <div id="records-list" class="divide-y divide-gray-100">
            <div class="flex items-center justify-center h-32 text-gray-400">
                <div class="text-center">
                    <i class="fa fa-spinner fa-spin text-lg mb-2"></i>
                    <p>加载记录中...</p>
                </div>
            </div>
        </div>

        <div id="empty-state" class="hidden flex flex-col items-center justify-center p-12 text-gray-400">
            <div class="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                <i class="fa fa-file-text-o text-2xl"></i>
            </div>
            <h3 class="text-lg font-medium mb-1">暂无充电记录</h3>
            <p class="text-sm text-center max-w-md">有车辆完成充电后，记录将显示在这里</p>
        </div>
    </div>
</main>

<script>
    // 返回按钮功能
    document.getElementById('back-button').addEventListener('click', () => {
        history.back();
    });

    // 生成唯一日期标识（如20250816）
    function getDateKey(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}${month}${day}`;
    }

    // 初始化当前日期显示
    function initCurrentDate() {
        const now = new Date();
        const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
        document.getElementById('current-date').textContent = now.toLocaleDateString('zh-CN', options);
        return now;
    }

    // 格式化时间：补零
    function formatTime(date) {
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');
        return `${hour}:${minute}:${second}`;
    }

    // 格式化时长显示
    function formatDuration(minutes) {
        // 限制最大时长为8小时
        minutes = Math.min(minutes, 480);

        if (minutes < 60) {
            return `${minutes}分钟`;
        }
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return `${hours}小时${mins > 0 ? mins + '分钟' : ''}`;
    }

    // 计算两个日期之间的分钟差
    function getMinutesBetweenDates(start, end) {
        return Math.floor((end - start) / (1000 * 60));
    }

    // 生成有效的时间范围（最大8小时，确保结束时间不超过当前时间）
    function generateValidTimeRange(today, usedTimeRanges, isCharging = false) {
        const MAX_DURATION_MINUTES = 480; // 8小时 = 480分钟
        let startDate, endDate, durationMinutes;
        const maxAttempts = 10; // 防止死循环的最大尝试次数
        let attempts = 0;
        const now = new Date(); // 当前时间，用于确保结束时间不超过此时

        do {
            attempts++;

            if (isCharging) {
                // 充电中订单：开始时间从当前时间倒推，随机15分钟到8小时之间
                const maxBackMinutes = MAX_DURATION_MINUTES; // 最大可倒推8小时
                const backMinutes = Math.floor(Math.random() * (maxBackMinutes - 15 + 1)) + 15;

                // 计算开始时间 = 当前时间 - 倒推分钟数
                startDate = new Date(now);
                startDate.setMinutes(now.getMinutes() - backMinutes);

                // 充电中订单的结束时间就是当前时间（确保不超过当前时间）
                endDate = new Date(now);
                durationMinutes = backMinutes;
            } else {
                // 非充电中订单：开始时间在当天00:00 ~ 当前时间前15分钟
                const currentHour = now.getHours();
                const currentMinute = now.getMinutes();

                // 确保开始时间不晚于当前时间前15分钟
                const maxStartHour = currentHour;
                const maxStartMinute = currentHour === maxStartHour ? Math.max(0, currentMinute - 15) : 59;

                const startHour = Math.floor(Math.random() * (maxStartHour + 1));
                const startMinute = startHour === maxStartHour
                    ? Math.floor(Math.random() * (maxStartMinute + 1))
                    : Math.floor(Math.random() * 60);
                const startSecond = Math.floor(Math.random() * 60);

                startDate = new Date(today);
                startDate.setHours(startHour, startMinute, startSecond, 0);

                // 计算最大可能时长（不超过8小时且不跨天，且结束时间不超过当前时间）
                const maxPossibleDurationFromTime = Math.min(
                    MAX_DURATION_MINUTES,
                    (23 - startHour) * 60 + (59 - startMinute) // 当天剩余分钟数
                );

                // 计算到当前时间的剩余分钟数
                const timeToNowMinutes = Math.floor((now - startDate) / (1000 * 60)) - 15; // 至少提前15分钟结束
                const maxPossibleDuration = Math.min(maxPossibleDurationFromTime, timeToNowMinutes);

                // 确保有足够的时间生成订单
                if (maxPossibleDuration < 15) {
                    // 如果时间不足，调整开始时间更早一些
                    startDate.setMinutes(startDate.getMinutes() - 30);
                    // 重新计算最大可能时长
                    const newTimeToNowMinutes = Math.floor((now - startDate) / (1000 * 60)) - 15;
                    maxPossibleDuration = Math.min(MAX_DURATION_MINUTES, newTimeToNowMinutes);
                }

                // 充电时长：15分钟 ~ 最大可能时长
                durationMinutes = Math.floor(Math.random() * (maxPossibleDuration - 15 + 1)) + 15;
                endDate = new Date(startDate);
                endDate.setMinutes(startDate.getMinutes() + durationMinutes);

                // 最终检查确保结束时间不超过当前时间
                if (endDate > now) {
                    endDate = new Date(now);
                    endDate.setMinutes(now.getMinutes() - 15); // 确保结束时间至少在15分钟前
                    durationMinutes = getMinutesBetweenDates(startDate, endDate);
                }
            }

            // 检查时间是否冲突
        } while (attempts < maxAttempts &&
        usedTimeRanges.some(range =>
            (startDate >= range.start && startDate < range.end) ||
            (endDate > range.start && endDate <= range.end)
        ));

        if (attempts >= maxAttempts) {
            throw new Error('无法生成不冲突的时间，可能设备占用过满');
        }

        // 额外验证：确保计算的时长与实际时间差一致
        const actualDuration = getMinutesBetweenDates(startDate, endDate);
        if (Math.abs(actualDuration - durationMinutes) > 1) {
            console.warn(`时间计算不一致，修正时长: ${durationMinutes} -> ${actualDuration}`);
            durationMinutes = actualDuration;
        }

        return { startDate, endDate, durationMinutes };
    }

    // 生成充电记录数据（严格满足所有规则）
    function generateRecords(today, chargeData, deviceCount = 10) {
        const { orders: targetOrders, power: targetPower } = chargeData;
        const devices = Array.from({ length: deviceCount }, (_, i) => `设备${i + 1}`);
        const statusConfig = [
            { text: '已完成', tagClass: 'bg-success/10 text-success', hasCharge: true, hasEndTime: true, hasFee: true },
            { text: '充电中', tagClass: 'bg-primary/10 text-primary', hasCharge: true, hasEndTime: false, hasFee: false },
            { text: '已取消', tagClass: 'bg-gray-200 text-gray-600', hasCharge: false, hasEndTime: false, hasFee: false },
            { text: '充电失败', tagClass: 'bg-danger/10 text-danger', hasCharge: false, hasEndTime: false, hasFee: false }
        ];

        // 必须包含已取消/充电失败订单（总订单数 > targetOrders）
        const totalOrders = targetOrders + Math.max(1, Math.floor(Math.random() * 3)); // 额外1-3个已取消/失败订单
        const validOrderCount = targetOrders; // 已完成+充电中 = targetOrders

        // 设备占用状态：记录每个设备的【充电中订单】时间范围
        const deviceChargingRanges = devices.reduce((acc, dev) => {
            acc[dev] = []; // 仅记录“充电中”订单的时间范围
            return acc;
        }, {});

        const records = [];
        const todayDateStr = today.toLocaleDateString('zh-CN');
        const dateKey = getDateKey(today);
        let usedPower = 0; // 已使用电量（用于校验）

        // 先分配有效订单（已完成+充电中）
        for (let i = 0; i < validOrderCount; i++) {
            const device = devices[i % deviceCount]; // 均匀分配设备
            const status = i < validOrderCount * 0.7 ? statusConfig[0] : statusConfig[1]; // 7:3 分配已完成和充电中

            // 生成不冲突的时间
            let timeData;
            if (status.text === '充电中') {
                // 充电中订单：特殊处理，从当前时间倒推生成开始时间
                timeData = generateValidTimeRange(today, deviceChargingRanges[device], true);
                // 记录充电中订单的时间范围（用于后续冲突检查）
                deviceChargingRanges[device].push({
                    start: timeData.startDate,
                    end: timeData.endDate // 结束时间是当前时间
                });
            } else {
                // 已完成订单：常规时间生成
                timeData = generateValidTimeRange(today, []);
            }

            const startDateTime = `${todayDateStr} ${formatTime(timeData.startDate)}`;
            let endDateTime, duration, durationMinutes;

            if (status.text === '充电中') {
                // 充电中订单：时长是当前时间与开始时间的差值
                durationMinutes = timeData.durationMinutes;
                endDateTime = '充电中...';
                duration = formatDuration(durationMinutes);
            } else {
                // 其他订单：使用生成的时长
                durationMinutes = timeData.durationMinutes;
                endDateTime = `${todayDateStr} ${formatTime(timeData.endDate)}`;
                duration = formatDuration(durationMinutes);
            }

            // 电量：30-80度
            const power = Math.floor(Math.random() * 51) + 30; // 30-80
            usedPower += power;

            // 订单号
            const randomStr = Math.random().toString(36).toUpperCase().substr(2, 6);
            const orderNo = `CD${dateKey}${randomStr}`;

            // 费用
            const fee = (power * 1.1).toFixed(2);

            records.push({
                device,
                orderNo,
                startDateTime,
                endDateTime,
                startDate: timeData.startDate, // 存储原始Date对象用于验证
                endDate: timeData.endDate,     // 存储原始Date对象用于验证
                power,
                duration,
                durationMinutes,
                status: status.text,
                statusClass: status.tagClass,
                hasCharge: status.hasCharge,
                hasFee: status.hasFee,
                fee: status.hasFee ? fee : '0.00'
            });
        }

        // 分配已取消/充电失败订单（确保总订单数 > targetOrders）
        for (let i = validOrderCount; i < totalOrders; i++) {
            const device = devices[Math.floor(Math.random() * deviceCount)];
            // 随机分配已取消或充电失败状态
            const status = Math.random() > 0.5 ? statusConfig[2] : statusConfig[3];

            // 已取消/失败订单：常规时间生成
            const timeData = generateValidTimeRange(today, []);
            const startDateTime = `${todayDateStr} ${formatTime(timeData.startDate)}`;

            // 电量（虽已取消/失败，仍需符合30-80度规则，但不计入统计）
            const power = Math.floor(Math.random() * 51) + 30;

            // 订单号
            const randomStr = Math.random().toString(36).toUpperCase().substr(2, 6);
            const orderNo = `CD${dateKey}${randomStr}`;

            records.push({
                device,
                orderNo,
                startDateTime,
                endDateTime: '---',  // 已取消/失败订单结束时间用---
                startDate: timeData.startDate,
                endDate: timeData.endDate,
                power,
                duration: '---',      // 已取消/失败订单时长用---
                durationMinutes: 0,
                status: status.text,
                statusClass: status.tagClass,
                hasCharge: status.hasCharge,
                hasFee: status.hasFee,
                fee: '0.00'
            });
        }

        // 统计数据
        const completedOrders = records.filter(r => r.status === '已完成');
        const validOrders = records.filter(r => ['已完成', '充电中'].includes(r.status));
        const totalPower = completedOrders.reduce((sum, r) => sum + r.power, 0);
        const totalIncome = completedOrders.reduce((sum, r) => sum + parseFloat(r.fee), 0);

        // 严格校验：有效订单数=targetOrders，总电量≈targetPower（允许微小误差）
        if (Math.abs(totalPower - targetPower) > 1) {
            console.warn('电量误差过大，重新生成...');
            return generateRecords(today, chargeData, deviceCount);
        }

        return {
            records,
            stats: {
                validOrders: validOrders.length,
                totalPower: totalPower,
                totalIncome: totalIncome
            }
        };
    }

    // 验证并修正已完成订单的时间和时长
    function validateAndFixCompletedOrders(records) {
        const now = new Date();
        const fixedRecords = [...records];

        fixedRecords.forEach(record => {
            if (record.status === '已完成') {
                // 验证结束时间不超过当前时间
                if (record.endDate > now) {
                    console.warn(`订单 ${record.orderNo} 结束时间在当前时间之后，已修正`);
                    record.endDate = new Date(now);
                    record.endDate.setMinutes(now.getMinutes() - 15);
                    record.endDateTime = `${record.endDate.toLocaleDateString('zh-CN')} ${formatTime(record.endDate)}`;
                }

                // 重新计算时长确保与实际时间差一致
                const actualDuration = getMinutesBetweenDates(record.startDate, record.endDate);
                if (Math.abs(actualDuration - record.durationMinutes) > 1) {
                    console.warn(`订单 ${record.orderNo} 时长计算不一致，已修正: ${record.durationMinutes} -> ${actualDuration}`);
                    record.durationMinutes = actualDuration;
                    record.duration = formatDuration(actualDuration);
                }
            }
        });

        return fixedRecords;
    }

    // 渲染充电记录
    function renderChargingRecords() {
        const today = initCurrentDate();
        const dateKey = getDateKey(today);
        const chargeData = JSON.parse(localStorage.getItem('chargeData') || '{"orders": 10, "power": 500}'); // 默认数据

        // 检查缓存（当天数据不变，第二天重置）
        let cachedData = JSON.parse(localStorage.getItem('chargingRecordsCache') || '{}');

        if (!cachedData || cachedData.dateKey !== dateKey) {
            const newData = generateRecords(today, chargeData);
            cachedData = {
                dateKey: dateKey,
                records: newData.records,
                stats: newData.stats
            };
            localStorage.setItem('chargingRecordsCache', JSON.stringify(cachedData));
        } else {
            // 更新充电中订单的时长（因为是动态变化的）
            const now = new Date();
            cachedData.records.forEach(record => {
                if (record.status === '充电中') {
                    const startDate = new Date(record.startDateTime);
                    const timeDiffMs = now - startDate;
                    let durationMinutes = Math.floor(timeDiffMs / (1000 * 60));
                    // 确保时长不超过8小时
                    durationMinutes = Math.min(durationMinutes, 480);
                    record.duration = formatDuration(durationMinutes);
                    record.durationMinutes = durationMinutes;
                }
            });

            // 验证并修正已完成订单
            cachedData.records = validateAndFixCompletedOrders(cachedData.records);
        }

        // 更新统计数据
        document.getElementById('stat-orders').textContent = cachedData.stats.validOrders;
        document.getElementById('stat-power').textContent = `${cachedData.stats.totalPower.toFixed(2)} 度`;
        document.getElementById('stat-income').textContent = `¥${cachedData.stats.totalIncome.toFixed(2)}`;

        // 渲染记录列表
        const recordsList = document.getElementById('records-list');
        const emptyState = document.getElementById('empty-state');

        if (cachedData.records.length === 0) {
            recordsList.innerHTML = '';
            emptyState.classList.remove('hidden');
            return;
        }
        emptyState.classList.add('hidden');

        recordsList.innerHTML = '';
        cachedData.records.forEach(record => {
            const feeText = record.hasFee ? `¥${record.fee}` : '¥0.00';
            // 检查是否是已取消或充电失败状态
            const isCancelledOrFailed = ['已取消', '充电失败'].includes(record.status);

            const recordHtml = `
                    <div class="record-card">
                        <!-- 移动端视图 -->
                        <div class="p-4 md:hidden">
                            <div class="flex justify-between items-start mb-3">
                                <span class="font-medium">${record.device}</span>
                                <span class="status-tag ${record.statusClass}">${record.status}</span>
                            </div>
                            <div class="grid grid-cols-2 gap-2 mb-3 text-sm">
                                <div>
                                    <p class="text-gray-500 text-xs">订单号</p>
                                    <p class="truncate">${record.orderNo}</p>
                                </div>
                                <div>
                                    <p class="text-gray-500 text-xs">充电量</p>
                                    <p class="${!record.hasCharge ? 'text-gray-400' : ''}">${record.power.toFixed(2)} 度</p>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-2 text-sm mb-2">
                                <div>
                                    <p class="text-gray-500 text-xs">开始时间</p>
                                    <p class="text-gray-600">${record.startDateTime}</p>
                                </div>
                                <div>
                                    <p class="text-gray-500 text-xs">结束时间</p>
                                    <p class="text-gray-600">${isCancelledOrFailed ? '---' : record.endDateTime}</p>
                                </div>
                            </div>
                            <div class="flex justify-between items-center text-sm">
                                <div>
                                    <p class="text-gray-500 text-xs">时长</p>
                                    <p>${isCancelledOrFailed ? '---' : record.duration}</p>
                                </div>
                                <div>
                                    <p class="text-gray-500 text-xs">费用</p>
                                    <p class="${record.hasFee ? 'text-success font-medium' : 'text-gray-400'}">${feeText}</p>
                                </div>
                            </div>
                        </div>

                        <!-- 桌面端视图 -->
                        <div class="hidden md:grid md:grid-cols-7 gap-2 px-6 py-4 items-center">
                            <div class="col-span-1 font-medium">${record.device}</div>
                            <div class="col-span-1 text-sm">${record.orderNo}</div>
                            <div class="col-span-1 text-sm text-gray-600">${record.startDateTime}</div>
                            <div class="col-span-1 text-sm text-gray-600">${isCancelledOrFailed ? '---' : record.endDateTime}</div>
                            <div class="col-span-1 text-sm ${!record.hasCharge ? 'text-gray-400' : ''}">${record.power.toFixed(2)} 度</div>
                            <div class="col-span-1 text-sm">${isCancelledOrFailed ? '---' : record.duration}</div>
                            <div class="col-span-1">
                                <span class="status-tag ${record.statusClass}">${record.status}</span>
                                <p class="text-xs mt-1 ${record.hasFee ? 'text-success' : 'text-gray-400'}">${feeText}</p>
                            </div>
                        </div>
                    </div>
                `;
            recordsList.innerHTML += recordHtml;
        });

        // 验证规则
        const validation = {
            设备充电中订单数: {},
            时长合规性: {
                超过8小时的订单: []
            },
            充电中开始时间验证: {
                符合倒推规则: true,
                异常订单: []
            },
            结束时间验证: {
                不超过当前时间: true,
                异常订单: []
            },
            时长与时间差一致性: {
                全部一致: true,
                异常订单: []
            }
        };

        // 验证每个设备的充电中订单数
        window.devices.forEach(dev => {
            const chargingCount = cachedData.records.filter(r =>
                r.device === dev && r.status === '充电中'
            ).length;
            validation.设备充电中订单数[dev] = {
                数量: chargingCount,
                合规: chargingCount <= 1
            };
        });

        const now = new Date();
        // 验证所有订单时长不超过8小时且结束时间不超过当前时间
        cachedData.records.forEach((record) => {
            if (record.durationMinutes > 480) { // 480分钟 = 8小时
                validation.时长合规性.超过8小时的订单.push({
                    订单号: record.orderNo,
                    设备: record.device,
                    状态: record.status,
                    时长分钟: record.durationMinutes
                });
            }

            // 验证充电中订单的开始时间是否在当前时间的8小时内
            if (record.status === '充电中') {
                const startTime = new Date(record.startDateTime);
                const timeDiffHours = (now - startTime) / (1000 * 60 * 60);

                if (timeDiffHours < 0 || timeDiffHours > 8) {
                    validation.充电中开始时间验证.符合倒推规则 = false;
                    validation.充电中开始时间验证.异常订单.push({
                        订单号: record.orderNo,
                        时间差小时: timeDiffHours.toFixed(2),
                        开始时间: record.startDateTime
                    });
                }
            }

            // 验证结束时间不超过当前时间
            if (record.status === '已完成' && record.endDateTime !== '---') {
                const endTime = new Date(record.endDateTime);
                if (endTime > now) {
                    validation.结束时间验证.不超过当前时间 = false;
                    validation.结束时间验证.异常订单.push({
                        订单号: record.orderNo,
                        结束时间: record.endDateTime,
                        当前时间: now.toLocaleString()
                    });
                }
            }

            // 验证时长与时间差一致
            if (record.status === '已完成') {
                const startTime = new Date(record.startDateTime);
                const endTime = new Date(record.endDateTime);
                const actualDuration = getMinutesBetweenDates(startTime, endTime);

                if (Math.abs(actualDuration - record.durationMinutes) > 1) {
                    validation.时长与时间差一致性.全部一致 = false;
                    validation.时长与时间差一致性.异常订单.push({
                        订单号: record.orderNo,
                        记录时长: record.durationMinutes,
                        实际时长: actualDuration,
                        差值: Math.abs(actualDuration - record.durationMinutes)
                    });
                }
            }
        });
        validation.时长合规性.整体合规 = validation.时长合规性.超过8小时的订单.length === 0;

        console.log('=== 订单规则验证结果 ===');
        console.log(validation);
    }

    // 监听chargeData变化（仅当天数据不变时不刷新）
    window.addEventListener('storage', (e) => {
        if (e.key === 'chargeData') {
            const today = new Date();
            const dateKey = getDateKey(today);
            const cachedData = JSON.parse(localStorage.getItem('chargingRecordsCache') || '{}');

            if (!cachedData || cachedData.dateKey !== dateKey) {
                renderChargingRecords();
            }
        }
    });

    // 页面加载初始化
    window.addEventListener('DOMContentLoaded', () => {
        // 全局设备列表
        window.devices = Array.from({ length: 10 }, (_, i) => `设备${i + 1}`);

        // 若localStorage无chargeData，生成合理默认值
        if (!localStorage.getItem('chargeData')) {
            const demoChargeData = {
                orders: 12,        // 目标有效订单数
                power: 600,        // 目标总耗电量
                todayFinalPower: 800,
                todayFinalUsers: 14
            };
            localStorage.setItem('chargeData', JSON.stringify(demoChargeData));
        }

        renderChargingRecords();

        // 每5分钟更新一次充电中订单的时长
        setInterval(renderChargingRecords, 5 * 60 * 1000);
    });
</script>
</body>
</html>